import React, {Component} from 'react';
import {withFormik} from "formik";
import NavHeader from '../../../../components/NavHeader/NavHeader';
import { require2 } from '../../../../netWork';
import styles from './index.module.css'
import * as yup from 'yup';
import { Toast } from 'antd-mobile';

const REG_UNAME = /^[a-zA-Z_\d]{5,8}$/;
const RGE_PWD = /^[a-zA-Z_\d]{5,12}$/;
class Regist extends Component {
    render() {
        const {values, handleSubmit, handleChange,handleBlur, errors,touched} = this.props;
        return (
            <div className={styles.root}>
                <NavHeader>账号注册</NavHeader>
                <form className={styles.form}>
                    <div className={styles.user}>
                        <input type="text" className='input1' value={values.username} name='username'
                               placeholder='请输入账号'
                               onBlur={handleBlur}
                               onChange={handleChange}/>
                    </div>
                    {errors.username && touched.username &&(<div className={styles.errors}>{errors.username}</div>)}
                    <div className={styles.user}>
                        <input type="passWord" className='input1' value={values.password} name='password'
                               placeholder='请输入密码'
                               onBlur={handleBlur}
                               onChange={handleChange}/>
                    </div>
                    {errors.password && touched.password &&(<div className={styles.errors}>{errors.password}</div>)}
                    <div className={styles.login} onClick={handleSubmit}>注册</div>
                </form>
            </div>
        );
    }
}



Regist = withFormik({
    // 提供状态
    mapPropsToValues:() => ({username: '', password: ''}),
    handleSubmit:(value,{props}) =>{
        require2({
            url:'user/registered',
            data:{username:value.username,password:value.password}
        }).then(res =>{
            console.log(res)
            if(res.status === 200){
                props.history.replace('/login')
            }else if(res.status === 400){
                Toast.info(res.description,2,null)
            }
        })
    },
     /*表单验证*/
     validationSchema:yup.object().shape({
        username:yup.string().required('账号为必填项').matches(REG_UNAME,'长度5-8，只能出现数字，字母下划线'),
        password:yup.string().required('密码为必填项').matches(RGE_PWD,'长度5-12，只能出现数字，字母下划线'),
        })
})(Regist)

export default Regist